/**
 * 自动补全弹窗组件
 * 显示智能补全建议
 */

import React, { useEffect, useState } from 'react';
import { Card, List, Tag, Space, Typography } from 'antd';
import { CheckOutlined, ThunderboltOutlined } from '@ant-design/icons';
import type { AutocompleteOption } from '@/stores/copilot.store';
import './style.css';

const { Text } = Typography;

interface AutocompletePopupProps {
  options: AutocompleteOption[];
  visible: boolean;
  position?: { top: number; left: number };
  selectedIndex?: number;
  onSelect: (optionId: string) => void;
  onDismiss: () => void;
}

/**
 * 获取补全类型标签
 */
const getTypeTag = (type: AutocompleteOption['type']) => {
  const tagMap = {
    word: { text: '词', color: 'blue' },
    sentence: { text: '句', color: 'green' },
    paragraph: { text: '段', color: 'purple' },
  };

  const { text, color } = tagMap[type];
  return (
    <Tag color={color} style={{ fontSize: 10, padding: '0 4px' }}>
      {text}
    </Tag>
  );
};

/**
 * 获取置信度颜色
 */
const getConfidenceColor = (confidence: number): string => {
  if (confidence >= 0.9) return '#52c41a';
  if (confidence >= 0.8) return '#1890ff';
  if (confidence >= 0.7) return '#faad14';
  return '#d9d9d9';
};

export const AutocompletePopup: React.FC<AutocompletePopupProps> = ({
  options,
  visible,
  position = { top: 0, left: 0 },
  selectedIndex = 0,
  onSelect,
  onDismiss,
}) => {
  const [currentIndex, setCurrentIndex] = useState(selectedIndex);

  useEffect(() => {
    setCurrentIndex(selectedIndex);
  }, [selectedIndex]);

  useEffect(() => {
    if (!visible) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setCurrentIndex((prev) => Math.min(prev + 1, options.length - 1));
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        setCurrentIndex((prev) => Math.max(prev - 1, 0));
      } else if (e.key === 'Tab' || e.key === 'Enter') {
        e.preventDefault();
        if (options[currentIndex]) {
          onSelect(options[currentIndex].id);
        }
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onDismiss();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [visible, options, currentIndex, onSelect, onDismiss]);

  if (!visible || options.length === 0) {
    return null;
  }

  return (
    <div
      className="autocomplete-popup"
      style={{
        top: position.top,
        left: position.left,
      }}
    >
      <Card
        className="autocomplete-card"
        size="small"
        bordered
        title={
          <Space size={4}>
            <ThunderboltOutlined style={{ color: '#1890ff' }} />
            <span>AI补全建议</span>
            <Text type="secondary" style={{ fontSize: 11 }}>
              (Tab接受，Esc关闭)
            </Text>
          </Space>
        }
      >
        <List
          className="autocomplete-list"
          dataSource={options}
          renderItem={(option, index) => (
            <List.Item
              className={`autocomplete-item ${
                index === currentIndex ? 'autocomplete-item-selected' : ''
              }`}
              onClick={() => onSelect(option.id)}
              onMouseEnter={() => setCurrentIndex(index)}
            >
              <div className="autocomplete-item-content">
                <div className="autocomplete-item-header">
                  <Space size={4}>
                    {getTypeTag(option.type)}
                    <div
                      className="confidence-indicator"
                      style={{
                        backgroundColor: getConfidenceColor(option.confidence),
                      }}
                      title={`置信度: ${Math.round(option.confidence * 100)}%`}
                    />
                  </Space>
                  {index === currentIndex && (
                    <CheckOutlined style={{ color: '#1890ff' }} />
                  )}
                </div>

                <div className="autocomplete-text">
                  {option.text}
                </div>

                <div className="autocomplete-meta">
                  <Text type="secondary" style={{ fontSize: 11 }}>
                    置信度: {Math.round(option.confidence * 100)}%
                  </Text>
                </div>
              </div>
            </List.Item>
          )}
        />

        <div className="autocomplete-footer">
          <Text type="secondary" style={{ fontSize: 11 }}>
            使用 ↑↓ 键选择，Tab 或 Enter 接受
          </Text>
        </div>
      </Card>
    </div>
  );
};
